package com.castle.fortress.admin.pay.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.castle.fortress.admin.core.annotation.CastleLog;
import com.castle.fortress.admin.core.constants.GlobalConstants;
import com.castle.fortress.admin.pay.dto.PayAliConfigDto;
import com.castle.fortress.admin.pay.dto.PaySceneDto;
import com.castle.fortress.admin.pay.dto.PayWxConfigDto;
import com.castle.fortress.admin.pay.entity.PaySceneEntity;
import com.castle.fortress.admin.pay.enums.PayTypeEnum;
import com.castle.fortress.admin.pay.service.PayAliConfigService;
import com.castle.fortress.admin.pay.service.PaySceneService;
import com.castle.fortress.admin.pay.service.PayWxConfigService;
import com.castle.fortress.admin.utils.ExcelUtils;
import com.castle.fortress.common.entity.DynamicExcelEntity;
import com.castle.fortress.common.entity.RespBody;
import com.castle.fortress.common.enums.OperationTypeEnum;
import com.castle.fortress.common.enums.YesNoEnum;
import com.castle.fortress.common.exception.BizException;
import com.castle.fortress.common.respcode.BizErrorCode;
import com.castle.fortress.common.respcode.GlobalRespCode;
import com.castle.fortress.common.utils.CommonUtil;
import com.castle.fortress.common.utils.ConvertUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 支付场景表 控制器
 *
 * @author castle
 * @since 2022-07-07
 */
@Api(tags="支付场景表管理控制器")
@Controller
public class PaySceneController {
    @Autowired
    private PaySceneService paySceneService;
    @Autowired
    private PayAliConfigService payAliConfigService;
    @Autowired
    private PayWxConfigService payWxConfigService;

    /**
     * 支付场景表的分页展示
     * @param paySceneDto 支付场景表实体类
     * @param current 当前页
     * @param size  每页记录数
     * @return
     */
    @CastleLog(operLocation = "支付场景表分页展示", operType = OperationTypeEnum.QUERY)
    @ApiOperation("支付场景表分页展示")
    @GetMapping("/pay/payScene/page")
    @ResponseBody
    @RequiresPermissions("pay:payScene:pageList")
    public RespBody<IPage<PaySceneDto>> pagePayScene(PaySceneDto paySceneDto, @RequestParam(required = false) Integer current, @RequestParam(required = false)Integer size){
        Integer pageIndex= current==null? GlobalConstants.DEFAULT_PAGE_INDEX:current;
        Integer pageSize= size==null? GlobalConstants.DEFAULT_PAGE_SIZE:size;
        Page<PaySceneDto> page = new Page(pageIndex, pageSize);
        IPage<PaySceneDto> pages = paySceneService.pagePayScene(page, paySceneDto);

        return RespBody.data(pages);
    }

    /**
     * 支付场景表的列表展示
     * @param paySceneDto 支付场景表实体类
     * @return
     */
    @CastleLog(operLocation = "支付场景表列表展示", operType = OperationTypeEnum.QUERY)
    @ApiOperation("支付场景表列表展示")
    @GetMapping("/pay/payScene/list")
    @ResponseBody
    public RespBody<List<PaySceneDto>> listPayScene(PaySceneDto paySceneDto){
        List<PaySceneDto> list = paySceneService.listPayScene(paySceneDto);
        return RespBody.data(list);
    }

    /**
     * 支付场景表保存
     * @param paySceneDto 支付场景表实体类
     * @return
     */
    @CastleLog(operLocation = "支付场景表保存", operType = OperationTypeEnum.INSERT)
    @ApiOperation("支付场景表保存")
    @PostMapping("/pay/payScene/save")
    @ResponseBody
    @RequiresPermissions("pay:payScene:save")
    public RespBody<String> savePayScene(@RequestBody PaySceneDto paySceneDto){
        if(paySceneDto == null ){
            throw new BizException(GlobalRespCode.PARAM_MISSED);
        }
        RespBody checkResult = paySceneService.checkColumnRepeat(paySceneDto);
        if(!checkResult.isSuccess()){
            return checkResult;
        }
        PaySceneEntity paySceneEntity = ConvertUtil.transformObj(paySceneDto,PaySceneEntity.class);
        if(paySceneService.save(paySceneEntity)){
            //异步保存配置信息
            paySceneService.asynSaveConfig(paySceneEntity);
            return RespBody.data("保存成功");
        }else{
            return RespBody.fail(GlobalRespCode.OPERATE_ERROR);
        }
    }

    /**
     * 支付场景表编辑
     * @param paySceneDto 支付场景表实体类
     * @return
     */
    @CastleLog(operLocation = "支付场景表编辑", operType = OperationTypeEnum.UPDATE)
    @ApiOperation("支付场景表编辑")
    @PostMapping("/pay/payScene/edit")
    @ResponseBody
    @RequiresPermissions("pay:payScene:edit")
    public RespBody<String> updatePayScene(@RequestBody PaySceneDto paySceneDto){
        if(paySceneDto == null || paySceneDto.getId() == null || paySceneDto.getId().equals(0L)){
            throw new BizException(GlobalRespCode.PARAM_MISSED);
        }
        //不允许修改场景编码
        paySceneDto.setCode(null);
        PaySceneEntity paySceneEntity = ConvertUtil.transformObj(paySceneDto,PaySceneEntity.class);
        if(paySceneService.updateById(paySceneEntity)){
            return RespBody.data("保存成功");
        }else{
            return RespBody.fail(GlobalRespCode.OPERATE_ERROR);
        }
    }

    /**
     * 支付场景表删除
     * @param id
     * @return
     */
    @CastleLog(operLocation = "支付场景表删除", operType = OperationTypeEnum.DELETE)
    @ApiOperation("支付场景表删除")
    @PostMapping("/pay/payScene/delete")
    @ResponseBody
    @RequiresPermissions("pay:payScene:delete")
    public RespBody<String> deletePayScene(@RequestParam Long id){
        if(id == null ){
            throw new BizException(GlobalRespCode.PARAM_MISSED);
        }
        PaySceneEntity paySceneEntity = paySceneService.getById(id);
        PayAliConfigDto payAliConfigDto = new PayAliConfigDto();
        payAliConfigDto.setSceneCode(paySceneEntity.getCode());
        payAliConfigDto.setStatus(YesNoEnum.YES.getCode());
        List<PayAliConfigDto> aliList = payAliConfigService.listPayAliConfig(payAliConfigDto);
        if(aliList!=null&&aliList.size()>0){
            throw new BizException(BizErrorCode.PAY_SCENE_DEL_ERROR);
        }
        PayWxConfigDto payWxConfigDto = new PayWxConfigDto();
        payWxConfigDto.setSceneCode(paySceneEntity.getCode());
        payWxConfigDto.setStatus(YesNoEnum.YES.getCode());
        List<PayWxConfigDto> wxList = payWxConfigService.listPayWxConfig(payWxConfigDto);
        if(wxList!=null&&wxList.size()>0){
            throw new BizException(BizErrorCode.PAY_SCENE_DEL_ERROR);
        }
        if(paySceneService.removeById(id)) {
            paySceneService.asynDelConfig(paySceneEntity);
            return RespBody.data("保存成功");
        }else{
            return RespBody.fail(GlobalRespCode.OPERATE_ERROR);
        }
    }


    /**
     * 支付场景表详情
     * @param id 支付场景表id
     * @return
     */
    @CastleLog(operLocation = "支付场景表详情", operType = OperationTypeEnum.QUERY)
    @ApiOperation("支付场景表详情")
    @GetMapping("/pay/payScene/info")
    @ResponseBody
    @RequiresPermissions("pay:payScene:info")
    public RespBody<PaySceneDto> infoPayScene(@RequestParam Long id){
        if(id == null){
            throw new BizException(GlobalRespCode.PARAM_MISSED);
        }
        PaySceneEntity paySceneEntity = paySceneService.getById(id);
        PaySceneDto paySceneDto = ConvertUtil.transformObj(paySceneEntity,PaySceneDto.class);

        return RespBody.data(paySceneDto);
    }

	/**
     * 动态表头导出 依据展示的字段导出对应报表
     * @param dynamicExcelEntity
     * @param response
     * @throws Exception
     */
    @CastleLog(operLocation = "支付场景表导出", operType = OperationTypeEnum.EXPORT)
	@PostMapping("/pay/payScene/exportDynamic")
	@ApiOperation("动态表头导出，依据展示的字段导出对应报表")
	public void exportDynamic(@RequestBody DynamicExcelEntity<PaySceneDto> dynamicExcelEntity, HttpServletResponse response) throws Exception {
		List<PaySceneDto> list = paySceneService.listPayScene(dynamicExcelEntity.getDto());
		//字典、枚举、接口、json常量等转义后的列表数据 根据实际情况初始化该对象，null为list数据直接导出
		List<List<Object>> dataList = null;
		/**
        * 根据实际情况初始化dataList,可参照 com.castle.fortress.admin.system.controller.TmpDemoController类中方法：exportDynamic
        */
		ExcelUtils.exportDynamic(response,dynamicExcelEntity.getFileName()+".xlsx",null,list,dynamicExcelEntity.getHeaderList(),dataList);
	}

    /**
     * 场景支付开关控制列表
     * @param sceneDto 场景对象
     * @return
     */
    @CastleLog(operLocation = "场景支付开关控制列表", operType = OperationTypeEnum.QUERY)
    @ApiOperation("场景支付开关控制列表")
    @GetMapping("/pay/payScene/configList")
    @ResponseBody
    @RequiresPermissions("pay:payScene:configEdit")
    public RespBody<Map<String,Object>> configList(PaySceneDto sceneDto){
        if(CommonUtil.verifyParamNull(sceneDto,sceneDto.getCode())){
            throw new BizException(GlobalRespCode.PARAM_MISSED);
        }
        Map<String,Object> map = new HashMap<>();
        //支付宝配置
        PayAliConfigDto payAliConfigDto = new PayAliConfigDto();
        payAliConfigDto.setSceneCode(sceneDto.getCode());
        List<PayAliConfigDto> aliList=payAliConfigService.listPayAliConfig(payAliConfigDto);
        for(PayAliConfigDto dto:aliList){
            PayTypeEnum typeEnum = PayTypeEnum.getByCode(dto.getPayTypeCode());
            dto.setPayTypeName(typeEnum.getDesc());
        }
        map.put("ALI",aliList);
        //微信配置
        PayWxConfigDto payWxConfigDto = new PayWxConfigDto();
        payWxConfigDto.setSceneCode(sceneDto.getCode());
        List<PayWxConfigDto> wxList = payWxConfigService.listPayWxConfig(payWxConfigDto);
        for(PayWxConfigDto dto:wxList){
            PayTypeEnum typeEnum = PayTypeEnum.getByCode(dto.getPayTypeCode());
            dto.setPayTypeName(typeEnum.getDesc());
        }
        map.put("WX",wxList);
        return RespBody.data(map);
    }



}
